package com.asset.dispoal.file.feature.service.command;

import com.asset.dispoal.file.feature.domain.db.entity.FileFeatureTable;
import com.asset.dispoal.file.feature.domain.db.mapper.FileFeatureTableMapper;
import com.asset.dispoal.file.feature.dto.FileFeatureTableCreateRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.file.FileUtil;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;

@Component
public class CreateFileFeatureTableCommand implements BaseCommand<FileFeatureTableCreateRequest, Result> {

    @Autowired
    Environment environment;

    @Autowired
    FileFeatureTableMapper fileFeatureTableMapper;

    @Autowired
    BaseIdeable<String> ideable;

    @SneakyThrows
    @Override
    public Result execute(FileFeatureTableCreateRequest request) {
        String id = ideable.generateId();
        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        String headUrl = environment.getProperty("file.evidence.url");
        String featureFolder = environment.getProperty("file.feature.url");
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(File.separator)
                .append(featureFolder)
                .append(File.separator)
                .append(request.getAssetInstBatchId())
                .append(File.separator);

        File checkDirFile = new File(headUrl + strBuilder);
        if (!checkDirFile.exists()) {
            FileUtil.createDirectory(checkDirFile, true);
        }
        String suffix = request.getFile().getOriginalFilename().substring(request.getFile().getOriginalFilename().lastIndexOf("."));
        String url = strBuilder.append(id).append(suffix).toString();
        if (request.getFile() != null) {
            request.getFile().transferTo(new File(headUrl + url));
        }
        FileFeatureTable fileFeatureTable = new FileFeatureTable();
        fileFeatureTable.setId(id);
        fileFeatureTable.setUrl(url);
        fileFeatureTable.setName(request.getName());
        fileFeatureTable.setAssetInstBatchId(request.getAssetInstBatchId());
        fileFeatureTable.setCreateUserId(userId);
        fileFeatureTable.setCreateTime(DateTimeUtil.currentDate());
        fileFeatureTableMapper.insert(fileFeatureTable);
        return Result.ok();
    }

}
